package com.momo.hr.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/***
 *  权限判断器,判断当前用户是否具备当前的已经分配的角色
 *  accessDecisionManager需要实现 AccessDecisionManager接口。
 *  实现方法decide(Authentication authentication, Object object,
 *  Collection<ConfigAttribute> configAttributes) 来做权限决策
 *  authentication可获取当前用户拥有的角色集合
 *  configAttributes 路径拦截处理中查询到的，能访问当前路径的角色集合
 */
@Component
public class CustomMyDecisionManager implements AccessDecisionManager {


    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //遍历当前请求需要的角色
        for (ConfigAttribute configAttribute : collection) {
            String attribute = configAttribute.getAttribute();
            System.err.println("当前角色:"+collection);
            //如果当前的访问路径没有对应的角色信息，就去判断档当前用户是否已经登录
            if("ROLE_LOGIN".equals(attribute)){
                //判断当前用户是匿名用户（也就是所谓的没有登录）
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("没有登录，请返回主页登录");
                } else {
                    return;
                }

            } else {
                //拿到当前已经登录用户的用户角色
                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();//获取当前用户登录的角色
                //遍历集合，查看当前集合中是否有对应的
                for (GrantedAuthority authority : authorities) {
                    if(authority.getAuthority().equals(attribute)){
                        return;
                    }
                }
            }
        }
         throw new AccessDeniedException("权限不足请联系管理员");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
